package com.kingyun.gpsinspection.purificationservice.services.som.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.Device;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.device.JsmDeviceService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.employee.JsmEmployeeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.FacadeWorkOrderService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.InfoflowService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomFileService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomWorkOrderService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.FinishTaskWebService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

/**
 * 工单相关service实现类
 * Created by yangcs on 2016/11/21.
 */
public class SomWorkOrderServiceImpl implements SomWorkOrderService {

    private static Logger logger = LoggerFactory.getLogger(SomWorkOrderServiceImpl.class);

    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private UnitStepResultMapper unitStepResultMapper;
    @Autowired(required = false)
    private FinishTaskWebService finishTaskWebService;
    @Autowired
    private FacadeWorkCellResultMapper facadeWorkCellResultMapper;
    @Autowired
    private FacadeOperatingUnitResultMapper facadeOperatingUnitResultMapper;
    @Autowired
    private FacadeUnitStepResultMapper facadeUnitStepResultMapper;
    @Autowired
    private FacadeUnitStepItemResultMapper facadeUnitStepItemResultMapper;
    @Autowired
    private OrderCountMapper orderCountMapper;
    @Autowired
    private SomFileService fileService;
    @Autowired
    private FacadeWorkOrderMapper facadeWorkOrderMapper;
    //    @Autowired(required = false)
//    private OutAutomaticExaminationService outAutomaticExaminationService;
    @Autowired
    private WorkOrderUserMapper workOrderUserMapper;
    @Autowired
    private FacadeWorkOrderService facadeWorkOrderService;
    @Autowired
    private InfoflowService infoflowService;
    @Autowired
    private JsmDeviceService jsmDeviceService;
    @Autowired
    private JsmEmployeeService jsmEmployeeService;

    /**
     * 工单查看列表
     *
     * @param workOrder 查询参数
     * @return
     */
    @Override
    public JSONObject list(WorkOrder workOrder) {
        JSONObject jsonObject = new JSONObject();
        workOrder.setLimit(workOrder.getLimit() == null ? 10 : workOrder.getLimit());
        workOrder.setOffset(workOrder.getOffset() == null ? 0 : workOrder.getOffset());

        if(StringUtils.isNotBlank(workOrder.getUserId())){
            workOrder.setUserList(Arrays.asList(workOrder.getUserId().split(",")));
        }
        jsonObject.put("total", workOrderMapper.queryCount(workOrder));
        jsonObject.put("rows", workOrderMapper.queryList(workOrder));
        return jsonObject;
    }

    /**
     * 根据工单ID查询工单
     * @param workOrderId 工单ID
     * @return
     */
    @Override
    public WorkOrder queryById(String workOrderId) {
        return workOrderMapper.queryById(workOrderId);
    }

    /**
     * 遗留工单列表
     *
     * @return
     */
    @Override
    public JSONObject unfinishList(WorkOrder workOrder) {
        JSONObject jsonObject = new JSONObject();
        workOrder.setLimit(workOrder.getLimit() == null ? 10 : workOrder.getLimit());
        workOrder.setOffset(workOrder.getOffset() == null ? 0 : workOrder.getOffset());
        if(StringUtils.isNotBlank(workOrder.getUserId())){
            workOrder.setUserList(Arrays.asList(workOrder.getUserId().split(",")));
        }
        jsonObject.put("total", workOrderMapper.queryUnfinishCount(workOrder));
        jsonObject.put("rows", workOrderMapper.queryUnfinishList(workOrder));
        return jsonObject;
    }

    /**
     * 遗留工单提醒
     *
     * @param workOrderId 工单ID
     * @return
     */
    @Override
    public Integer updateTimeById(String workOrderId) {
        return workOrderMapper.updateTimeById(workOrderId);
    }

    /**
     * 工单台帐
     *
     * @param workOrder 查询参数
     * @return
     */
    @Override
    public JSONObject order(WorkOrder workOrder) {
        JSONObject jsonObject = new JSONObject();
        workOrder.setLimit(workOrder.getLimit() == null ? 10 : workOrder.getLimit());
        workOrder.setOffset(workOrder.getOffset() == null ? 0 : workOrder.getOffset());
        jsonObject.put("total", workOrderMapper.queryOrderCount(workOrder));

        List<WorkOrder> list = workOrderMapper.queryOrderList(workOrder);
        List<WorkOrder> newList = new ArrayList<>();
        if( list != null && list.size() > 0 ){
            for( WorkOrder order : list ){
                order.setUserId( getOrderUser(order.getWorkOrderId()) );
                newList.add(order);
            }
        }

        jsonObject.put("rows", JSON.toJSON(newList));
        return jsonObject;
    }

    /**
     * 作业条件准备
     *
     * @param workOrder 查询参数
     * @return
     */
    @Override
    public JSONObject opcList(WorkOrder workOrder) {
        JSONObject jsonObject = new JSONObject();
        workOrder.setLimit(workOrder.getLimit() == null ? 10 : workOrder.getLimit());
        workOrder.setOffset(workOrder.getOffset() == null ? 0 : workOrder.getOffset());
        jsonObject.put("total", workOrderMapper.queryOpcCount(workOrder));
        jsonObject.put("rows", JSON.toJSON(workOrderMapper.queryOpcList(workOrder)));
        return jsonObject;
    }

    /**
     * 作业条件确认
     *
     * @param workOrder 查询参数
     * @return
     */
    @Override
    public JSONObject sureListAjax(WorkOrder workOrder) {
        JSONObject jsonObject = new JSONObject();
        workOrder.setLimit(workOrder.getLimit() == null ? 10 : workOrder.getLimit());
        workOrder.setOffset(workOrder.getOffset() == null ? 0 : workOrder.getOffset());
        jsonObject.put("total", workOrderMapper.querySureCount(workOrder));
        jsonObject.put("rows", JSON.toJSON(workOrderMapper.querySureList(workOrder)));
        return jsonObject;
    }

    /**
     * 遗留工单申请
     *
     * @param workOrderId 工单id
     * @return
     */
    @Override
    public int updateCanFinish(String workOrderId, Integer canFinish, String userId, String reason) {
        Map map = new HashMap();
        map.put("workOrderId", workOrderId);
        map.put("canFinish", canFinish);
        workOrderMapper.updateCanFinish(map);
        map.put("userId", userId);
        map.put("applyId", UniqueUtil.uuid());
        map.put("reason", reason);
        return workOrderMapper.insertApply(map);
    }

    @Override
    public int updateStatus(String workOrderId, Integer status) {
        Map map = new HashMap();
        map.put("workOrderId", workOrderId);
        map.put("status", status);
        return workOrderMapper.updateStatus(map);
    }

    /**
     * 已完成工单查询步骤
     * @param workOrderId 工单id
     * @param cellId      操作单元/工作内容id
     * @param stepVersion 版本
     * @param cellResultId 结果id
     * @return
     */
    @Override
    public List<UnitStepResult> findByWorkOrderId(String workOrderId, String cellId, BigDecimal stepVersion, String cellResultId) {
        Map map = new HashMap();
        map.put("workOrderId", workOrderId);
        map.put("cellId", cellId);
        map.put("stepVersion", stepVersion);
        map.put("cellResultId", cellResultId);
        List<UnitStepResult> list;
        if( StringUtils.isNotBlank(cellId) ){
            list = unitStepResultMapper.findByWorkOrderId(map);
        }else{
            // 自定义巡检 2个版本
            int category = facadeWorkOrderMapper.getCategoryById(workOrderId);
            if( category == 0 ){
                // 为0表示是第一版本，保存工单对应的stepId
                list = unitStepResultMapper.findByWorkOrderIdNoCellId(map);
            }else{
                // 不为0表示为第二版本，保存工单对应标准的id和大类
                list = unitStepResultMapper.findByWorkOrderIdNoCellIdAndCategory(map);
            }
        }
        List<UnitStepResult> newList = new ArrayList<>();
        // 工单完成时查询每个步骤的平均耗时
        if (list != null && list.size() > 0 && StringUtils.isNotBlank(cellResultId)) {
            for (UnitStepResult result : list) {
                result.setAvgExecuteDuring(unitStepResultMapper.queryAvg(result.getStepId()));
                newList.add(result);
            }
        } else {
            newList = list;
        }
        return newList;
    }

    /**
     * 执行工单 获取步骤
     * @param workOrderId
     * @param cellId
     * @param stepVersion
     * @return
     */
    @Override
    public List<UnitStepResult> findByWorkOrderId(String workOrderId, String cellId, BigDecimal stepVersion) {
        Map map = new HashMap();
        map.put("workOrderId", workOrderId);
        map.put("cellId", cellId);
        map.put("stepVersion", stepVersion);
        List<UnitStepResult> list;
        if( StringUtils.isNotBlank(cellId) ){
            list = unitStepResultMapper.findByWorkOrderId2(map);
        }else{
            // 自定义巡检 2个版本
            int category = facadeWorkOrderMapper.getCategoryById(workOrderId);
            if( category == 0 ){
                // 为0表示是第一版本，保存工单对应的stepId
                list = unitStepResultMapper.findByWorkOrderIdNoCellId2(map);
            }else{
                // 不为0表示为第二版本，保存工单对应标准的id和大类
                list = unitStepResultMapper.findByWorkOrderIdNoCellId2AndCategory(map);
            }
        }
        List<UnitStepResult> newList = new ArrayList<>();
        // 步骤数据项
        if (list != null && list.size() > 0) {
            for (UnitStepResult result : list) {
                result.setDataItems(JSON.toJSONString(facadeWorkOrderService.getDataItemsByStepId(result.getStepId(), null)));
                newList.add(result);
            }
        } else {
            newList = list;
        }
        return newList;
    }

    /**
     * 按照ID查询
     *
     * @param workOrderId 工单id
     * @return
     */
    @Override
    public WorkOrder selectById(String workOrderId) {
        return workOrderMapper.selectById(workOrderId);
    }


    /**
     * 工单上报
     *
     * @param result
     */
    @Override
    public String addOrder(FacadeWorkCellResult result, String userId) {
        List<File> infoflowFiles = new ArrayList<>();
        result.setCellResultId(UniqueUtil.uuid());
        // 插入工单结果信息
        result.setCreateUserId(userId);
        result.setFinishTimeDate(new Date(result.getFinishTime()));
        facadeWorkCellResultMapper.insert(result);
        // 更新工单状态
        Map map = new HashMap<>();
        map.put("workOrderId", result.getWorkOrderId());
        map.put("status", 6);
        workOrderMapper.updateSataus(map);
        // 插入工单多个完成人 开始
        String finishUsers = result.getFinishUsers();
        if (StringUtils.isNotBlank(finishUsers)) {
            String[] users = finishUsers.split(",");
            List<WorkOrderUser> list = new ArrayList<>();
            WorkOrderUser workOrderUser;
            for (int i = 0; i < users.length; i++) {
                workOrderUser = new WorkOrderUser();
                workOrderUser.setWorkOrderUserId(UniqueUtil.uuid());
                workOrderUser.setUserId(users[i]);
                workOrderUser.setWorkOrderId(result.getWorkOrderId());
                workOrderUser.setOrgId(jsmEmployeeService.queryByKeyId(users[i]).getOrgId());
                list.add(workOrderUser);
            }
            workOrderUserMapper.insertUser(list);
        }
        // 插入工单多个完成人 结束
        // 插入工单关联设备 开始
        String dev = result.getDevs();
        if (StringUtils.isNotBlank(dev)) {
            try {
                Device device = new Device();
                device.setDeviceId(dev);
                jsmDeviceService.CycleCalculation(device);
            } catch (Exception e) {
                logger.error("更新维保周期接口出错:deviceId=" + dev);
                e.printStackTrace();
            }
            String[] devs = dev.split(",");
            List<WorkOrderDev> list = new ArrayList<>();
            WorkOrderDev workOrderDev;
            for (int i = 0; i < devs.length; i++) {
                workOrderDev = new WorkOrderDev();
                workOrderDev.setWorkOrderId(result.getWorkOrderId());
                workOrderDev.setWorkOrderDevId(UniqueUtil.uuid());
                workOrderDev.setDeviceId(devs[i]);
                list.add(workOrderDev);
            }
            workOrderUserMapper.insertDev(list);
        }
        // 插入工单关联设备 结束
        // 插入工单表单项信息 开始
        List<FacadeOperatingUnitResult> items = result.getItems();
        // 不为空则循环
        if (items != null && items.size() > 0) {
            for (FacadeOperatingUnitResult r : items) {
                r.setInsertTimeDate(new Date(r.getInsertTime()));
                r.setUnitResultId(UniqueUtil.uuid());
                r.setCellResultId(result.getCellResultId());
                r.setCreatorId(userId);
                // 插入表单数据项信息
                facadeOperatingUnitResultMapper.insert(r);
                // r.getPropertyOpc()不为空时要调用C的接口
                // TODO: 2017/3/15
            }
        }
        // 插入工单表单项信息 结束
        // 插入步骤信息 开始
        List<FacadeUnitStepResult> steps = result.getSteps();
        List<FacadeUnitStepItemResult> stepItems;
        List<File> files;
        // 不为空则循环
        if (steps != null && steps.size() > 0) {
            for (FacadeUnitStepResult s : steps) {
                s.setExecuteTimeDate(new Date(s.getExecuteTime()));
                s.setCellResultId(result.getCellResultId());
                s.setCreateUserId(userId);
                s.setStepResultId(UniqueUtil.uuid());
                facadeUnitStepResultMapper.insert(s);
                // 插入步骤数据项信息
                stepItems = s.getItems();
                // 不为空则循环数据
                if (stepItems != null && stepItems.size() > 0) {
                    for (FacadeUnitStepItemResult sitem : stepItems) {
                        sitem.setInsertTimeDate(new Date(sitem.getInsertTime()));
                        sitem.setStepResultId(s.getStepResultId());
                        sitem.setCreatorId(userId);
                        sitem.setItemResultId(UniqueUtil.uuid());
                        facadeUnitStepItemResultMapper.insert(sitem);
                    }
                }
                // 插入步骤文件信息
                files = s.getFiles();
                // 不为空则循环数据
                if (files != null && files.size() > 0) {
                    for (File f : files) {
                        infoflowFiles.add(f);
                        f.setBusinessId(s.getStepResultId());
                        if (f.getFileType() == 0) {
                            f.setFileType(File.IMG_TYPE);
                        }
                        f.setFileId(UniqueUtil.uuid());
                        fileService.insert(f);
                    }
                }
            }
        }
        try {
            // 插入步骤信息 结束 最后调用任务接口
            finishTaskWebService.finishTaskByTaskId(selectById(result.getWorkOrderId()).getTaskId(), userId);
        } catch (Exception e) {
            logger.error("完成工单时，任务接口出错:" + e.getMessage(), e);
            e.printStackTrace();
        }
        try {
            // 考核接口
            WorkCellResult workCellResult = new WorkCellResult();
            workCellResult.setWorkOrderId(result.getWorkOrderId());
            workCellResult.setCreateopid(StringUtils.isNotBlank(result.getFinishUser()) ? result.getFinishUser() : result.getFinishUsers());
//            outAutomaticExaminationService.addWorkOderCheckresults(workCellResult);
        } catch (Exception e) {
            logger.error("完成工单时，考核接口出错:" + e.getMessage(), e);
            e.printStackTrace();
        }
        try {
            infoflowService.addInfoflowByFinishOrder(result.getWorkOrderId(),
                    StringUtils.isNotBlank(result.getFinishUser()) ? result.getFinishUser() : result.getFinishUsers(), result.getFinishTime(), userId, infoflowFiles);
        } catch (Exception e) {
            logger.error("完成工单时，工作动态接口出错:" + e.getMessage(), e);
            e.printStackTrace();
        }
        return result.getCellResultId();
    }

    /**
     * 更新工单信息
     *
     * @param workOrder
     * @return
     */
    @Override
    public int updateWorkOrder(WorkOrder workOrder) {
        return workOrderMapper.updateWorkOrder(workOrder);
    }

    /**
     * 更新工单状态
     *
     * @param workOrderId
     * @param status
     * @return
     */
    @Override
    public int updateSataus(String workOrderId, int status, String remark) {
        Map map = new HashMap<>();
        map.put("workOrderId", workOrderId);
        map.put("status", status);
        map.put("remark", remark);
        return workOrderMapper.updateSataus(map);
    }

    /**
     * 工单统计
     *
     * @param workOrder
     * @return
     */
    @Override
    public JSONObject orderCount(WorkOrder workOrder) {
        JSONObject jsonObject = new JSONObject();
        List<OrderCount> list = orderCountMapper.selectOrderCountList(workOrder);
        jsonObject.put("total", list.size());
        jsonObject.put("rows", JSON.toJSON(list));
        return jsonObject;
    }

    /**
     * 根据工单的任务类型统计工单数量
     *
     * @param workOrder
     * @return
     */
    @Override
    public List<OrderCount> orderTaskTypeCount(WorkOrder workOrder) {
        return orderCountMapper.orderTaskTypeCount(workOrder);
    }

    /**
     * 整体完成未完成饼图统计
     *
     * @param workOrder
     * @return
     */
    @Override
    public List<OrderCount> orderStatusCount(WorkOrder workOrder) {
        return orderCountMapper.orderStatusCount(workOrder);
    }

    /**
     * 工单统计-工单列表
     *
     * @param workOrder
     * @return
     */
    @Override
    public JSONObject countData(WorkOrder workOrder) {
        JSONObject jsonObject = new JSONObject();
        workOrder.setLimit(workOrder.getLimit() == null ? 10 : workOrder.getLimit());
        workOrder.setOffset(workOrder.getOffset() == null ? 0 : workOrder.getOffset());
        jsonObject.put("total", workOrderMapper.countDataCount(workOrder));
        jsonObject.put("rows", workOrderMapper.countData(workOrder));
        return jsonObject;
    }

    @Override
    public String getOrderUser(String workOrderId) {
        return workOrderMapper.getOrderUser(workOrderId);
    }

}
